package office.pdf.pdfbox;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.concurrent.FastThreadLocalThread;
import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeCollection;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.fontbox.util.autodetect.FontFileFinder;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.FopFactoryBuilder;
import org.apache.fop.fonts.FontManager;
import org.apache.pdfbox.contentstream.PDContentStream;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.encoding.Encoding;
import org.apache.pdfbox.pdmodel.font.encoding.StandardEncoding;
import org.apache.pdfbox.pdmodel.font.encoding.WinAnsiEncoding;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.util.Matrix;
import org.docx4j.Docx4J;
import org.docx4j.XmlUtils;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.convert.out.fo.renderers.FORendererApacheFOP;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import technology.tabula.*;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;
import wiki.xsx.core.pdf.doc.XEasyPdfDocument;
import wiki.xsx.core.pdf.template.XEasyPdfTemplate;
import wiki.xsx.core.pdf.template.datasource.XEasyPdfTemplateXMLDataSource;
import wiki.xsx.core.pdf.template.doc.XEasyPdfTemplateDocument;
import wiki.xsx.core.pdf.template.doc.page.XEasyPdfTemplatePage;
import wiki.xsx.core.pdf.template.doc.page.XEasyPdfTemplatePageComponent;
import wiki.xsx.core.pdf.template.handler.XEasyPdfTemplateHandler;

import java.awt.*;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 参考
 *  - pdfbox 快速指南：https://iowiki.com/pdfbox/pdfbox_quick_guide.html
 *  - pdfbox 官网：https://pdfbox.apache.org/blog/
 *  - x-easy-pdf 官网：https://x-easypdf.cn/
 *  - x-easy-pdf API：https://apidoc.gitee.com/dromara/x-easypdf/
 *  - pdfbox API：https://javadoc.io/doc/org.apache.pdfbox/pdfbox/2.0.27/index.html
 *  - xsl fop 标准：https://www.runoob.com/xslfo/obj-inline.html
 *
 * @author: zhanglu
 * @date: 2023/7/24 11:00
 * @modify: 修改人信息, 修改内容 2023/7/24 11:00
 */
public class PdfToWordTest {

    public static void main(String[] args) throws Exception {
//        PDDocument document = PDDocument.load(new File("/Users/zhanglu/Desktop/tmp/pdfbox/输变电工程质量检测工作手册.pdf"));
//        for (PDPage page : document.getPages()) {
//            PDFStreamParser parser = new PDFStreamParser(page);
//            parser.parse();
//            List<Object> tokens = parser.getTokens();
//            System.out.println(tokens.toString());
//        }


//        //得到pdf的页数
//        int pagenumber = document.getNumberOfPages();
//        String fileName="/Users/zhanglu/Desktop/tmp/pdfbox/输变电工程质量检测工作手册.docx";
//        FileOutputStream fos = new FileOutputStream(fileName);
//        //设置输出字符集为UTF-8 因此该word应该使用UTF-8格式打开 如果你出现乱码那么你可以自己修改一下这里的格式
//        Writer writer = new OutputStreamWriter(fos, "UTF-8");
//        PDFTextStripper stripper = new PDFTextStripper();
//        stripper.setSortByPosition(true);// 排序
//        stripper.setStartPage(1);// 设置转换的开始页
//        stripper.setEndPage(pagenumber);// 设置转换的结束页
//        stripper.writeText(document, writer);
//        writer.close();
//        document.close();

//        byte[] pdfBytes = FileUtil.readBytes("/Users/zhanglu/Desktop/tmp/PDF、OFD签章文件/1.pdf");
//        String text = "国网浙江省电力公司 张某某 2023-10-24    国网浙江省电力公司 张某某 2023-10-24    国网浙江省电力公司 张某某 2023-10-24    国网浙江省电力公司 张某某 2023-10-24";
//        float fontSize = 12;
//        int[] color = {128,128,128};
//        int rowSpace = 120;
//        int colSpace = 0;
//        FileUtil.writeBytes(waterMark(pdfBytes, text, fontSize, color, rowSpace, colSpace), "/Users/zhanglu/Desktop/tmp/PDF、OFD签章文件/1s.pdf");

//        byte[] imgBytes = FileUtil.readBytes("/Users/zhanglu/Desktop/下载.png");
//        byte[] bytes = pngWaterMark(imgBytes, text);
//        FileUtil.writeBytes(bytes, "/Users/zhanglu/Desktop/下载s.png");


//        String data = FileUtil.readUtf8String("/Users/zhanglu/Desktop/pdf.txt");
//        String pdf = JSONUtil.parseObj(data).getStr("data");
//        FileUtil.writeBytes(Base64.decode(pdf), "/Users/zhanglu/Desktop/sign.pdf");

//        String res = FileUtil.readUtf8String("/Users/zhanglu/Desktop/1.txt");
//        List<String> nums = new ArrayList<>();
//        List<JSONObject> s = new ArrayList<>();
//        JSONUtil.parseObj(res).getJSONArray("data").forEach(o -> {
//            JSONObject jo = (JSONObject) o;
////            String updateTime = jo.getStr("updateTime");
////            long tag = DateUtil.parse("2023-11-10 02:00:00").getTime();
////            long time = DateUtil.parse(updateTime).getTime();
////            if(time <= tag){
////                s.add(jo);
////            }
//            nums.add(jo.getStr("signatureFileNum"));
//        });
//        System.out.println(s.toString());
//        List<List<String>> partition = Lists.partition(nums, 50);
//        for (List<String> ids : partition) {
//            System.out.println(ids.size());
//            System.out.println(StrUtil.join(",", ids));
//        }

//        String res = FileUtil.readUtf8String("/Users/zhanglu/Desktop/pdf.txt");
//        String data = JSONUtil.parseObj(res).getStr("data");
//        System.out.println(data);
//        FileUtil.writeBytes(Base64.decode(data), "/Users/zhanglu/Desktop/表7.ofd");

//        String s = FileUtil.readUtf8String("/Users/zhanglu/Desktop/1.txt");
//        String data = JSONUtil.parseObj(s).getStr("data");
//        FileUtil.writeBytes(Base64.decode(data), "/Users/zhanglu/Desktop/1.pdf");
//        System.out.println(IdUtil.fastSimpleUUID());
//        System.out.println(IdUtil.fastSimpleUUID());
//        System.out.println(Base64.encode(FileUtil.readBytes("/Users/zhanglu/Downloads/签字.png")));




    }

    /** 
     * 给文件添加水印
     *
     * @param pdfBytes 需要添加水印的文件
     * @param text 水印文字 (统一宋体)
     * @param fontSize 字体大小 (默认是10)
     * @param color 字体颜色：{r, g, b}
     * @param rowSpace 行间距  
     * @param colSpace 列间距 距离左边
     * @throws IOException 异常
     */
    public static byte[] waterMark(byte[] pdfBytes, String text, float fontSize, int[] color, int rowSpace, int colSpace) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 加载PDF文件
        PDDocument document = PDDocument.load(pdfBytes);
        document.setAllSecurityToBeRemoved(true);

        // 遍历PDF文件，在每一页加上水印
        for (PDPage page : document.getPages()) {
            PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
            // 加载水印字体
            TrueTypeCollection trueTypeCollection = new TrueTypeCollection(new FileInputStream("/Users/zhanglu/Desktop/tmp/SimSun.ttc"));
            TrueTypeFont trueTypeFont = trueTypeCollection.getFontByName("SimSun");
            PDFont font = PDType0Font.load(document, trueTypeFont, true);
            PDExtendedGraphicsState r = new PDExtendedGraphicsState();
            // 设置透明度
            r.setNonStrokingAlphaConstant(0.2f);
            r.setAlphaSourceFlag(true);
            stream.setGraphicsStateParameters(r);
            // 设置水印字体颜色
            if (color.length == 3) {
                stream.setNonStrokingColor(color[0], color[1], color[2]);
            }
            stream.beginText();
            stream.setFont(font, fontSize);
            stream.newLineAtOffset(0, 0);
            // 获取PDF页面大小
            float pageHeight = page.getMediaBox().getHeight();
            // 根据纸张大小添加水印，30度倾斜
            for (int h = -100; h < pageHeight; h = h + rowSpace) {
                stream.setTextMatrix(Matrix.getRotateInstance(0.3, colSpace, h));
                stream.showText(text);
            }
            // 结束渲染，关闭流
            stream.endText();
            stream.restoreGraphicsState();
            stream.close();
        }
        document.save(outputStream);
        return outputStream.toByteArray();
    }

    public static byte[] pngWaterMark(byte[] imgBytes, String text){
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        BufferedImage image = ImgUtil.read(new ByteArrayInputStream(imgBytes));
        int height = image.getHeight();
        int width = image.getWidth();
        int rowSpace = 60;
        AffineTransform affineTransform = new AffineTransform();
        affineTransform.rotate(Math.toRadians(-30), 0 ,0);
        Font font = new Font("SimSun", Font.PLAIN, 16).deriveFont(affineTransform);
        for (int h = - (height) + 60; h < height; h = h + rowSpace) {
            image = (BufferedImage) ImgUtil.pressText(image, text, new Color(0, 0, 0), font, - width, h, 1.0f);
        }
        ImgUtil.writePng(image, outputStream);
        return outputStream.toByteArray();
    }


    /*
            山东天润电气集团有限公司-改前
            {"id":"0e7d8b3f3d8d411ba049141fb112fa48","enterpriseId":"db7fd9dd67dc42b8bbfb35d14a736a54", "enterpriseType": 0}
            {"id":"b09b393940034f47ad59b9cfcbb2f56a","enterpriseId":"1cddd827a3614c7d837613f96591c804", "enterpriseType": 1}
            山东天润电气集团有限公司-改后
            {"id":"0e7d8b3f3d8d411ba049141fb112fa48","enterpriseId":"1cddd827a3614c7d837613f96591c804", "enterpriseType": 1}
            {"id":"b09b393940034f47ad59b9cfcbb2f56a","enterpriseId":"db7fd9dd67dc42b8bbfb35d14a736a54", "enterpriseType": 0}

            衡阳雁能电力勘测设计咨询有限公司-改前
            {"id":"2c2751b94cd04042af23839d19b00920","enterpriseId":"7031a75454bb4225b58dc939a3a48545", "enterpriseType": 1}
            {"id":"09ef5dca89444d9d9c3dabe8de98134e","enterpriseId":"07E731C1B1BC2861E065000000000001", "enterpriseType": 0}
            衡阳雁能电力勘测设计咨询有限公司-改后
            {"id":"2c2751b94cd04042af23839d19b00920","enterpriseId":"07E731C1B1BC2861E065000000000001", "enterpriseType": 0}
            {"id":"09ef5dca89444d9d9c3dabe8de98134e","enterpriseId":"7031a75454bb4225b58dc939a3a48545", "enterpriseType": 1}

     */

}
